<script setup>
import { Upload } from '@element-plus/icons-vue'
import TextEitdor from '@/views/text/TextEitdor.vue'
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { insertWeek } from '@/api/insertweek'
import { selectTypeName } from '@/api/insertweek'


// 获取当前日期时间
const now = new Date();

// 格式化日期时间为 yyyy-MM-dd HH:mm:ss
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const formattedDateTime = formatDate(now);




const form = ref({
  leaveType: '', // 请假类型
  startDate: '', // 请假开始时间
  endDate: '', // 请假结束时间
  reason: '', // 请假原因
  description: '', // 请假描述
  applicant: '', // 申请人
  department: '' // 部门
})

const ruleForm = ref(null)
const userstore = useUserStore()
const user = userstore.user

const bumen = ref(null) // 部门id

const optionInfo = ref([])

const type = async () => {
  const res = await selectTypeName()
  console.log(res);
  optionInfo.value = res.data.data
  console.log(optionInfo.value);
}




const refresh = () => {
  // updateCurrentTime();
  bumen.value = null
  form.value = {
    typeDate: '', // 请假类型
    startTime: '', // 请假开始时间
    endTime: '', // 请假结束时间
    content: '', // 请假描述
    userId: user.id,  //用户id
    status:1  //默认状态
  }
}

// 表单校验规则
const rules = {
  leaveType: [
    { required: true, message: '请选择请假类型', trigger: 'change' },
  ],
  startDate: [
    { required: true, message: '请选择请假开始时间', trigger: 'change' },
  ],
  endDate: [
    { required: true, message: '请选择请假结束时间', trigger: 'change' },
  ],
  reason: [
    { required: true, message: '请输入请假原因', trigger: 'blur' },
    { max: 50, message: '请假原因不能超过50个字', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入请假描述', trigger: 'blur' },
  ],
}

// 组件挂载时初始化数据
onMounted(() => {
  type()
  form.value.applicant = user.id // 设置申请人
  if (user.departmentId) form.value.department = user.departmentId // 设置部门
})

// 提交请假申请
const submitLeave = async () => {
  if (form.value.description !== '<p><br></p>') {
    try {
      await ruleForm.value.validate() // 表单校验
      const res = await insertWeek({
        typeDate: form.value.typeDate,
        startTime: form.value.startTime, 
        endTime: form.value.endTime, 
        content: form.value.content,
        creatTime: formattedDateTime, //当前的创建时间
        userId: user.id,
        status:1
      }) // 调用请假接口
      if (res) {
        ElMessage.success('请假申请提交成功！')
      }
      refresh() // 重置表单
    } catch (error) {
      ElMessage.error('表单校验失败，请检查输入！')
    }
  } else {
    ElMessage.error('请假描述不能为空！')
  }
}
</script>

<template>
  <el-card>
    <el-button type="primary" style="width: 100px; text-align: center;" @click="refresh">
      重置
    </el-button>
    <h1 style="font-size: 30px; text-align: center; margin-bottom: 20px;">请假申请</h1>
    
    <el-form
      ref="ruleForm"
      style="max-width: 600px; margin: 0 auto;"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="demo-ruleForm"
      status-icon
    >
    
      <!-- 请假类型 -->
      <el-form-item label="请假类型" prop="typeDate">
        <el-select v-model="form.typeDate" placeholder="请选择" style="width: 150px;">
          <el-option v-for="option in optionInfo" :key="option.value" :label="option.nameType"
            :value="option.id" />
        </el-select>
      </el-form-item>

      <!-- 请假时间 -->
      <el-form-item label="请假时间" prop="startTime">
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="请选择开始日期"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item prop="endTime">
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="请选择结束日期"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <!-- 请假原因
      <el-form-item label="请假原因" prop="reason">
        <el-input v-model="form.reason" placeholder="请输入请假原因" />
      </el-form-item> -->

      <!-- 请假描述 -->
      <el-form-item label="请假描述" prop="content">
        <TextEitdor v-model="form.content" />
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitLeave">
          提交申请
          <el-icon class="el-icon--right"><Upload /></el-icon>
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
.el-card {
  margin: 5px;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h1 {
  color: #409eff;
  font-weight: bold;
}

.el-button {
  width: 100%;
}
</style>